﻿using System;
using System.Drawing;
using System.Web;
using System.Web.SessionState;

namespace Eff.Web
{
    /// <summary>
    /// 验证码 IHttpHandler
    /// 使用方法。1.添加IHttpHandler.ashx,然后继续此类
    ///           2.可以选择的重写一些参数
    /// </summary>
    public class ValidateImg : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 验证码随机字符,默认"0123456789"
        /// </summary>
        public virtual string CodeString { get { return "0123456789"; } }

        /// <summary>
        /// 验证码长度，默认4
        /// </summary>
        public virtual int CodeLength { get { return 4; } }

        /// <summary>
        /// 字体大小，默认11
        /// </summary>
        public virtual int FontSize { get { return 11; } }

        private const string SessionKey = "ValidateImg_validate_code";

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="code"></param>
        /// <param name="ignoreCase"></param>
        /// <returns></returns>
        public static bool Verify(string code, bool ignoreCase = true)
        {
            return string.Compare(HttpContext.Current.Session[SessionKey] as string, code, ignoreCase) == 0;
        }

        public void ProcessRequest(HttpContext context)
        {
            char[] chars = CodeString.ToCharArray();
            var random = new Random();

            string validateCode = string.Empty;
            for (int i = 0; i < CodeLength; i++)
            {
                char rc = chars[random.Next(0, chars.Length)];
                if (validateCode.IndexOf(rc) > -1)
                {
                    i--;
                    continue;
                }
                validateCode += rc;
            }
            context.Session[SessionKey] = validateCode;
            CreateImage(context.Response, validateCode);
        }

        /// <summary>
        /// 创建图片
        /// </summary>
        /// <param name="response"></param>
        /// <param name="checkCode"></param>
        private void CreateImage(HttpResponse response, string checkCode)
        {
            var iwidth = (int)((checkCode.Length * (FontSize + 0.5)));
            var image = new System.Drawing.Bitmap(iwidth, (int)(FontSize * (5 / 3.0)));
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.White);
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Chocolate, Color.Brown, Color.DarkCyan, Color.Purple };
            Random rand = new Random();

            //输出不同字体和颜色的验证码字符
            for (int i = 0; i < checkCode.Length; i++)
            {
                int cindex = rand.Next(7);
                Font f = new Font("Microsoft Sans Serif", FontSize);
                Brush b = new SolidBrush(c[cindex]);
                g.DrawString(checkCode.Substring(i, 1), f, b, (i * FontSize), 0, StringFormat.GenericDefault);
            }
            //画一个边框
            g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);

            //输出到浏览器
            var ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            response.ClearContent();
            response.ContentType = "image/Jpeg";
            response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


    }
}
